import React, { useEffect, useState } from 'react'
import { Layout } from '../components/Layout'
import { EmptyState, ErrorState } from '../components/States'

type Settings = {
  log_level: string
  ssh_timeout_seconds: number
  ssh_keepalive_seconds: number
  ws_heartbeat_seconds: number
  log_flush_threshold_bytes: number
  log_retention_days: number
}

export function SettingsPage(): JSX.Element {
  const [data, setData] = useState<Settings | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  const load = async () => {
    setError(null)
    try {
      const resp = await fetch('/api/settings/')
      if (!resp.ok) throw new Error(await resp.text())
      const json = await resp.json()
      setData(json)
    } catch (e: any) {
      setError(e.message)
    }
  }

  useEffect(() => { load() }, [])

  const save = async () => {
    if (!data) return
    setSaving(true)
    try {
      const resp = await fetch('/api/settings/', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
      if (!resp.ok) throw new Error(await resp.text())
      const json = await resp.json()
      setData(json)
      alert('保存成功（部分设置将立即生效）')
    } catch (e: any) {
      alert('保存失败：' + (e.message || ''))
    } finally {
      setSaving(false)
    }
  }

  return (
    <Layout>
      <div className="container">
        <div className="panel">
          <div className="header">
            <h3 className="title">系统设置</h3>
            <div className="toolbar">
              <button className="btn btn-sm" onClick={load}>刷新</button>
              <button className="btn btn-primary btn-sm" onClick={save} disabled={!data || saving}>保存</button>
            </div>
          </div>
          <div className="content">
            {error && <ErrorState message={error} onRetry={load} />}
            {!error && !data && <EmptyState title="加载中" description="正在获取配置..." />}
            {data && (
              <div className="form-grid">
                <div className="field">
                  <label className="muted">日志级别</label>
                  <select className="select" value={data.log_level} onChange={e => setData({ ...data, log_level: e.target.value })}>
                    {['DEBUG', 'INFO', 'WARNING', 'ERROR'].map(l => <option key={l} value={l}>{l}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label className="muted">SSH 超时（秒）</label>
                  <input className="input" type="number" value={data.ssh_timeout_seconds} onChange={e => setData({ ...data, ssh_timeout_seconds: Number(e.target.value) })} />
                </div>
                <div className="field">
                  <label className="muted">SSH KeepAlive（秒）</label>
                  <input className="input" type="number" value={data.ssh_keepalive_seconds} onChange={e => setData({ ...data, ssh_keepalive_seconds: Number(e.target.value) })} />
                </div>
                <div className="field">
                  <label className="muted">WS 心跳（秒）</label>
                  <input className="input" type="number" value={data.ws_heartbeat_seconds} onChange={e => setData({ ...data, ws_heartbeat_seconds: Number(e.target.value) })} />
                </div>
                <div className="field">
                  <label className="muted">日志落库阈值（字节）</label>
                  <input className="input" type="number" value={data.log_flush_threshold_bytes} onChange={e => setData({ ...data, log_flush_threshold_bytes: Number(e.target.value) })} />
                </div>
                <div className="field">
                  <label className="muted">日志保留天数</label>
                  <input className="input" type="number" value={data.log_retention_days} onChange={e => setData({ ...data, log_retention_days: Number(e.target.value) })} />
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </Layout>
  )
}

